var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
// const requestId = require('express-request-id').default;
const expressJWT = require('express-jwt').expressjwt
const session = require('express-session');
const multer = require("multer"); // zqc
// 导入配置文件
const config = require('./config')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors())
// 配置 session

//实例化multer，传递的参数对象，dest表示上传文件的存储路径 //zqc

app.use(session({
  secret: 'your_secret_key', // 用于签名 session ID 的密钥，建议使用随机字符串
  resave: false, // 强制保存 session 即使它并没有变化
  saveUninitialized: true, // 强制将未初始化的 session 存储
  cookie: { secure: false } // 如果是 HTTPS 环境，设置为 true
}));
// app.use(requestId());

let objMulter = multer({ dest: "./public/upload" }); //zqc
//实例化multer，传递的参数对象，dest表示上传文件的存储路径 //zqc
app.use(objMulter.any())//any表示任意类型的文件 //zqc

 // 响应数据的中间件
app.use(function (req, res, next) {
  // status = 0 为成功； status = 1 为失败； 默认将 status 的值设置为 1，方便处理失败的情况
  res.cc = function (code = 0,err, data = []) {
    if (data.length === 0) {
      res.send({
     // 状态
    code,
     // 状态描述，判断 err 是 错误对象 还是 字符串
     message: err instanceof Error ? err.message : err,
  })
    } else {
      res.send({
    // 状态
    code,
    // 状态描述，判断 err 是 错误对象 还是 字符串
    message: err instanceof Error ? err.message : err,
    data:  data,
  })
  }
 
  }
  next()
})



app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 路由之前解析token
// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
  path: [
     "/user/login",      // 精确匹配 /user/login
    "/user/captcha",
    "/liveStock/public/imgUpload",
    /^\/home\/.*/,
    /^\/manageLeft\/.*/,
    /^\/manageRight\/.*/,
    /^\/map\/.*/,
    /^\/trace\/.*/,
    /^\/weappUser\/.*/,
    /^\/upload\/.*/,
    /^\/file\/.*/,
  ]
}))

// app.use(expressJWT({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
//  path: [/.*/]
// }))

var indexRouter = require('./routes/index');
app.use('/', indexRouter);
// pc端
let userRouter = require('./routes/admin/users');
let deviceRouter = require('./routes/admin/device');
let liveStockRouter = require('./routes/admin/liveStock');
let mationRouter = require('./routes/admin/mation');
let reportRouter = require('./routes/admin/report');
let videoRouter = require('./routes/admin/video');
app.use('/user', userRouter);
app.use('/device', deviceRouter);
app.use('/liveStock', liveStockRouter);
app.use('/mation', mationRouter);
app.use('/report', reportRouter);
app.use('/video', videoRouter);

// 小程序
let homeRouter = require('./routes/weapp/home');
let manageLeftRouter = require('./routes/weapp/manageLeft');
let manageRightRouter = require('./routes/weapp/manageRight');
let mapRouter = require('./routes/weapp/map');
let traceRouter = require('./routes/weapp/trace');
let weappUserRouter = require('./routes/weapp/weappUser');
app.use('/home', homeRouter);
app.use('/manageLeft', manageLeftRouter);
app.use('/manageRight', manageRightRouter);
app.use('/map', mapRouter);
app.use('/trace', traceRouter);
app.use('/weappUser', weappUserRouter);

// 错误中间件
app.use(function (err, req, res, next) {

  // 捕获身份认证失败的错误 token
if (err.name === 'UnauthorizedError') return res.cc(1,'身份认证失败！')

  // 未知错误
  res.cc(err)
  })


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



app.listen(9999, () => {
  console.log('http://127.0.0.1:9999')
  
})

module.exports = app;
